import requests
import time
import os
import re
import json
from datetime import datetime
from translate import Translator

# 设置全局变量，headers 和 access_token
headers = {'Content-Type': 'application/json;charset=utf-8', 'User-Agent': 'Mozilla/5.0'}
access_token = "8078bf519af0add4e53849a110dfa7b8"
owner = "chenzhigao123"
repo = "my-hexo"


# 获取指定状态的所有issue
def get_issues_by_state(owner, repo, state):
    issue_url = f"https://gitee.com/api/v5/repos/{owner}/{repo}/issues?access_token={access_token}&state={state}"
    response = requests.get(issue_url, headers=headers)
    return response.json()


# 获取指定issue下面的所有评论
def get_comments_by_issue_number(owner, repo, number):
    comment_url = f'https://gitee.com/api/v5/repos/{owner}/{repo}/issues/{number}/comments?access_token={access_token}'
    response = requests.get(comment_url, headers=headers)
    comments = response.json()
    return comments


# 更新指定issue的信息
def update_issue_by_issue_number(owner, number, data):
    issue_url = f"https://gitee.com/api/v5/repos/{owner}/issues/{number}"
    data['access_token'] = access_token
    data['repo'] = repo
    response = requests.patch(issue_url, headers=headers, data=json.dumps(data))
    print(str(response.status_code))


# 文章模版
TEMPLATE = '''---
title: {}
date: {}
tags:
{}
---
{}
<!-- more -->
{}
'''
# 笔记文件根路径
POSTS_DIR_PATH = '/Users/zhigaochen/Desktop/chenzhigao/myblog/my-hexo/source/_posts'


# 构造文章标签内容
def construct_tags(article):
    labels = article.get('labels')
    tag_list = []
    for label in labels:
        tag_list.append('- ' + label.get('name'))
    article_tags = '\n'.join(tag_list)
    return article_tags


def cutItems(param):
    result = []
    for x in param:
        result.append(str(x).lower())
    return result


def simplify_title(text):
    # 去除标点符号、空格等特殊字符
    text = re.sub('[^\w\s]', '', text)

    # 将连续多个空格合并为单个空格
    result_list = cutItems(text.split())
    text = '-'.join(result_list)

    return text


# 根据文章标题生成英文名
def get_title_en_name(original_title):
    translator = Translator(from_lang='zh', to_lang='en')
    try:
        # 调用翻译函数进行翻译
        translated_title = translator.translate(original_title)
    except Exception as e:
        print("翻译失败:", str(e))
    else:
        simplified_title = simplify_title(translated_title)
        print("翻译结果:", simplified_title)
        return simplified_title + '.md'


# 创建并填充文件内容
def create_file_and_fill_content(article):
    # 根据创建时间创建目录 'created_at': '2024-06-18T20:34:06+08:00'->2024-07-10 11:08:36
    create_time = datetime.strptime(article.get('created_at')[0:19], '%Y-%m-%dT%H:%M:%S')
    # 解析日期时间字符串
    year = create_time.year
    month = create_time.month
    dir_name = os.path.join(POSTS_DIR_PATH, str(year), str(month).zfill(2))
    if not os.path.exists(dir_name):
        os.makedirs(dir_name)
    article_title = str(article.get('title')) # 文章标题
    article_create_time = str(create_time)    # 文章创建时间
    article_precis = str(article.get('body')) # 文章摘要
    number = article.get('number')
    comments = get_comments_by_issue_number(owner, repo, number)
    body_list = []
    for comment in comments:
        body_list.append(comment.get('body'))
    article_body = '\n\n'.join(body_list)     # 文章正文
    article_tags = construct_tags(article)    # 文章标签
    content = TEMPLATE.format(article_title, article_create_time, article_tags, article_precis, article_body)
    file_name = os.path.join(dir_name, get_title_en_name(article_title))
    with open(file_name, 'w') as file_obj:
        file_obj.write(content)
    time.sleep(5)

# 进行中状态改为已完成
def change_state_to_closed(article):
    number = article.get('number')
    data = {
        'state': 'closed'
    }
    update_issue_by_issue_number(owner, number, data=data)


if __name__ == '__main__':
    progressing_articles = get_issues_by_state(owner, repo, 'progressing')
    for article in progressing_articles:
        create_file_and_fill_content(article)
        change_state_to_closed(article)
